package com.xujc.dao.imp;

import com.xujc.dao.IDiscusDAO;
import com.xujc.entity.DiscuseEntity;
import com.xujc.entity.FormEntity;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;

/**
 * Created by xujc on 6/17/15.
 */
public class DiscusDAO extends HibernateDaoSupport implements IDiscusDAO {
    @Override
    public void deleteDiscus(int d_id) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        Query query = session.createQuery("delete DiscuseEntity where DId = ?");
        query.setParameter(0,d_id);
        query.executeUpdate();
        transaction.commit();
        session.close();


    }

    @Override
    public List<DiscuseEntity> getAllDiscusUnder(int f_id) {
        Session session=getSessionFactory().openSession();
        Query query = session.createQuery("from DiscuseEntity where FId=?");
        query.setParameter(0,f_id);
        List list = query.list();

            return list;
    }

    @Override
    public void editDiscus(int d_id, String content) {
        Session session=getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();

        Query query = session.createQuery("update DiscuseEntity set content = ? where DId = ?");
        query.setParameter(0,content);
        query.setParameter(1,d_id);
        query.executeUpdate();

        transaction.commit();
        session.close();
    }

    @Override
    public int publishDiscus(int u_id, int f_id, String content, String photoList) {
        Session session = getSessionFactory().openSession();
        Transaction transaction = session.beginTransaction();
        DiscuseEntity entity=new DiscuseEntity();
        entity.setContent(content);
        entity.setUId(u_id);
        entity.setFId(f_id);
        entity.setContent(content);
        entity.setPublishTime(Timestamp.from(Instant.now()));
        entity.setImages(photoList);

        session.save(entity);
        Query query = session.createQuery("from FormEntity where FId=?");
        query.setParameter(0, f_id);
        FormEntity formEntity = (FormEntity) query.uniqueResult();
        formEntity.setDiscuseNumber(formEntity.getDiscuseNumber()+1);
        formEntity.setLastActive(Timestamp.valueOf(LocalDateTime.now()));
        session.save(formEntity);

        transaction.commit();
        session.close();

        return entity.getDId();
    }

    @Override
    public DiscuseEntity getDiscus(int d_id) {
        Session session=getSessionFactory().openSession();
        Query query = session.createQuery("from DiscuseEntity where DId=?");
        query.setParameter(0,d_id);
        List list = query.list();

        return (DiscuseEntity) list.get(0);
    }
}
